﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace IbsImport
{
    /// <summary>
    /// 
    /// </summary>
    public class Mail
    {
        private string SMTP_SERVER_HOST { get; set; }
        private int SMTP_SERVER_PORT { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SMTP_SERVER_HOST"></param>
        /// <param name="SMTP_SERVER_PORT"></param>
        public Mail(string SMTP_SERVER_HOST, int SMTP_SERVER_PORT)
        {
            this.SMTP_SERVER_HOST = SMTP_SERVER_HOST;
            this.SMTP_SERVER_PORT = SMTP_SERVER_PORT;
        }

        /// <summary>
        /// Отправка электронного сообщения
        /// </summary>
        /// <param name="from">Отправитель</param>
        /// <param name="to">Получатель</param>
        /// <param name="subject">Тема сообщения</param>
        /// <param name="body">Текст сообщения</param>
        public void Send(string from, string to, string subject, string body)
        {
            SmtpClient client = new SmtpClient(this.SMTP_SERVER_HOST, this.SMTP_SERVER_PORT);
            client.UseDefaultCredentials = true;

            MailMessage message = new MailMessage();

            message.From = new MailAddress(from);

            if (to != null)
                to.Split(new char[] { ';', ',', ' ' }).ToList().ForEach(r =>
                {
                    if (r.Length != 0)
                        message.To.Add(new MailAddress(r));
                });

            message.Subject = subject;
            message.Body = body;

            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml = false;

            try
            {
                client.Send(message);
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy ||
                        status == SmtpStatusCode.MailboxUnavailable)
                    {
                        //Delivery failed - retrying in 3 seconds.");
                        System.Threading.Thread.Sleep(3000);
                        client.Send(message);
                    }
                    else
                    {
                        throw ex;
                        //Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
                    }
                }
            }
        }
    }
}
